<?php

namespace App\Task;

use App\Constants\CacheKey;
use App\Model\Meeting;
use App\Services\MeetingService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;

class SignStatusTask
{

    /**
     * @Inject
     * @var MeetingService
     */
    private $meetingService;

    public function exec()
    {
        $all = $this->meetingService->allNoFinishMeetings();
        if (!empty($all->all())) {
            $now = date('Y-m-d H:i:s');
            $begin = [];
            $end = [];
            $redis = di()->get(Redis::class);
            foreach ($all as $item) {
                if ($item['start_time'] <= $now && $item['end_time'] > $now) {
                    $begin[] = $item['id'];
                } elseif ($item['end_time'] <= $now) {
                    $end[] = $item['id'];
                    //结束时再次清空缓存
                    $key = sprintf(CacheKey::MEETING_GROUP_CHAT_KEY,  $item['id']);
                    $fd_key = sprintf(CacheKey::MEETING_GROUP_CHAT_FD_KEY, $item['id']);
                    if ($redis->exists($key)) {
                        $redis->del($key);
                    }
                    if ($redis->exists($fd_key)) {
                        $redis->del($fd_key);
                    }
                }
            }
            Meeting::query()->whereIn('id', $begin)->update(['status'=>1]);
            Meeting::query()->whereIn('id', $end)->update(['status'=>2]);
        }
    }

}